package ljl.alg.wangzheng_camp.round1.tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class _589_ntree_preorder {
    
    /**
     * 这个不想迭代了，递归吧就
     * */
    public List<Integer> preorder(Node root) {
        List<Integer> res = new ArrayList<>();
        dfs(root, res);
        return res;
    }
    void dfs(Node root, List<Integer> res) {
        if (root == null) return;
        res.add(root.val);
        for (Node child : root.children) {
            dfs(child, res);
        }
    }
    
    /**
     * 迭代！
     *
     * 前序这么简单吗？
     *
     * */
    public List<Integer> preorder2(Node root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) return res;
        LinkedList<Node> stack = new LinkedList<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Node node = stack.pop();
            res.add(node.val);
            for (int i = node.children.size() - 1; i >= 0 ; i--) {
                stack.push(node.children.get(i));
            }
        }
        return res;
    }
}
